package protocol

import (
	"context"
	"net"

	"gitee.com/go-course/go11/devcloud-mini/cmdb/conf"
	"gitee.com/go-course/go11/devcloud-mini/cmdb/logger"
	"github.com/infraboard/mcube/ioc"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"google.golang.org/grpc"
)

// 如果http 服务器使用哪个路由, 当做参数传递进来
func NewGrpc() *Grpc {
	return &Grpc{
		server: grpc.NewServer(
			grpc.ChainUnaryInterceptor(
				// 添加Grpc Trace中间件
				otelgrpc.UnaryServerInterceptor(),
			),
		),
	}
}

type Grpc struct {
	server *grpc.Server
}

func (g *Grpc) Start() error {
	// 2.1 加载grpc业务实现类
	ioc.LoadGrpcController(g.server)

	logger.L().Debug().Msgf("loaded controllers: %s", ioc.ListControllerObjectNames())

	// 2.3 启动grpc server
	lis, err := net.Listen("tcp", conf.C().Grpc.Address())
	if err != nil {
		return err
	}
	logger.L().Debug().Msgf("grpc server listen: %s", conf.C().Grpc.Address())
	return g.server.Serve(lis)
}

func (g *Grpc) Stop(ctx context.Context) {
	g.server.GracefulStop()
}
